<template>
  <div>
    <el-dialog
        title="导出文件"
        v-el-drag-dialog
        :visible="CCshow.outputShp"
        width="40%"
        :before-close="handleClose">
      <form class="layui-form myData" action="save" method="post" lay-filter="stuform">
        <div class="demo-input-suffix">
          导出名称：
          <el-input
              class="input-name"
              placeholder="请输入内容"
              v-model="nameinput"
              clearable>
          </el-input>
        </div>
        <div class="demo-input-suffix daihao-div">
          选择带号：
          <el-select
              class="selectDaihao"
              v-model="selectVal"
              placeholder="请选择坐标系带号"
              ref="select"
              style="width: 100%"
          >
            <el-input
                class="input"
                placeholder="输入关键字进行过滤"
                prefix-icon="el-icon-search"
                v-model="treeFilter"
                size="mini"
                clearable
            ></el-input>
            <el-option hidden key="id" :value="selectVal" :label="selectName">
            </el-option>
            <el-tree
                :data="treeData"
                :props="defaultProps"
                @node-click="handleNodeClick"
                :expand-on-click-node="false"
                :check-on-click-node="true"
                ref="tree"
                node-key="id"
                :default-expand-all="false"
                :filter-node-method="filterNode"
            >

          <span slot-scope="{ data }">
          <span>{{ data.label }}</span>
          <el-tag
              size="mini"
              style="margin: 0 10px"
              v-show="filterorgType(data.tag)"
          >{{ filterorgType(data.tag) }}</el-tag
          >
        </span>
            </el-tree>
          </el-select>
        </div>
      </form>
      <span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleOutput">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from "@/directive/el-dragDialog/";
import {writeShpFile,writeShpFile2} from "@/api/portal/ioGisFile";

export default {
  name: "OutputShp",
  data() {
    return {
      drawFeatures: [],
      nameinput:"",
      selectVal: "", // select框的绑定值
      selectName: "", // select框显示的name
      treeFilter: "", // 搜索框绑定值，用作过滤
      filterText: '',
      // 树形控件数据
      treeData: [
        {
          value: '4490',
          label: '经纬度'
        },
        {
          value: '4529',
          label: '41度带'
        },
        {
          value: '4530',
          label: '42度带'
        },
        {
          value: '4531',
          label: '43度带'
        },
        {
          value: '4532',
          label: '44度带'
        },
        {
          value: '4533',
          label: '45度带'
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 标签数组
      tagList: [
        {value: "701", label: "宝泉岭"}
      ],
    };
  },
  props: {
    CCshow: {
      type: Object,
      default() {
        return {
          // outputShp: false,
        }
      }
    },
    features: {
      type: Array,
      default() {
        return []
      }
    },

    /*isShowOut:null,*/
  },
  created() {
    let cc=this.CCshow;
    let aa=this.features;
  },
  methods: {
    // 结构树点击事件
    handleNodeClick(currentData) {
      let that = this;
      that.selectVal = currentData.value; // select绑定值为点击的选项的value
      that.selectName = currentData.label; // input中显示值为label
      that.treeFilter = ""; // 点击后搜索框清空
      that.$refs.select.blur(); // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
    },
    // 选项卡标签（可忽略，增值迭代需求）
    filterorgType(val) {
      let arr = this.tagList.filter((item) => {
        return item.value == val;
      });
      return arr.length ? arr[0].label : "";
    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输入条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true;
      let filterRes = data.label.indexOf(value) !== -1;
      return filterRes;
    },
    handleOutput() {
      let that = this;
      // that.drawFeatures = [];
      // that.overSource.forEachFeature(function (feature) {
      //   that.drawFeatures.push(feature);
      // });
      that.ExportShp(that.features, that.nameinput, "EPSG:" + that.selectVal);
      that.CCshow.outputShp = false;
    },
    /*
         * 选择features，导出shp。
         * @param {type} features  ol格式的features
         * @param {type} filename 导出的shp名称
         * @param {type} epsg  epsg的格式为'EPSG:4532' 这样的
         * @returns {undefined}
         */
    ExportShp: function (features, filename, epsg) {
      var geojson = new ol.format.GeoJSON();
      //let geomwkts = [];
      for (var i in features) {
        features[i].getGeometry().applyTransform(ol.proj.getTransform("EPSG:4490", epsg));
        //geomwkts.push(new ol.format.WKT().writeFeature(features[i]))
      }
      var geojsonstr = geojson.writeFeaturesObject(features);
      for (var i = 0; i < geojsonstr.features.length; i++) {
        /*下面这些是原来是在前台生成shp会出现的各种问题。用geotools之后就不用这么费劲的转换格式了。
        var feaCoors = geojsonstr.features[i].geometry.coordinates;
        if (geojsonstr.features[i].geometry.type == "MultiPolygon") {
          geojsonstr.features[i].geometry.type = "Polygon";
          var gjsj = [];
          for (var j = 0; j < feaCoors.length; j++) {
            gjsj.push(feaCoors[j][0]);
          }
          geojsonstr.features[i].geometry.coordinates = [];
          geojsonstr.features[i].geometry.coordinates.push(gjsj);
        } else if (feaCoors.length > 1) {
          geojsonstr.features[i].geometry.coordinates = [];
          geojsonstr.features[i].geometry.coordinates.push(feaCoors);
        }
         */
        var props = geojsonstr.features[i].properties;
        if(props!=null) {
          if (props.hasOwnProperty("smarea")) {
            props.garea = props.smarea;
          }
          //把超图相关的字段东西都删掉。smarea应该是椭球面积，很有用。改个名（garea）先导出来。
          delete props['smid'];
          delete props['smuserid'];
          delete props['smperimeter'];
          delete props['smgeometry'];
          delete props['smarea'];
          for (var j in props) {
            var value = props[j];
            geojsonstr.features[i].properties[j] = unescape(value.replace(/\\u/gi, '%u'));
          }
        }
      }
      let fd = new FormData();
      //fd.append("geoms", geomwkts.join("&&"));
      fd.append("geoms", JSON.stringify(geojsonstr));
      fd.append("epsg", epsg);
      fd.append("fname", this.nameinput);

    //  writeShpFile2(fd,this.nameinput)
      writeShpFile(fd,'blob').then(response => {
        //why20220323获取当前时间
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        let currentDate = date.getFullYear() + "" + month + "" + strDate
            + "_" + date.getHours() + "" + date.getMinutes() + "" + date.getSeconds();

    //    let blob = new Blob([response.data], {type: "application/zip"});
        let blob = new Blob([response], {type: "application/zip"});
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = filename; // 重命名文件
        link.click();
        URL.revokeObjectURL(url); // 释放内存
      }).catch(
          error => this.$message.error(error)
      );
    },
    handleClose() {
      let that = this;
      that.CCshow.outputShp = false;
    }
  },
  directives: {//到这里了，看看自定义组件怎么个用法
    elDragDialog,
  },
  watch: {
    // 搜索过滤，监听input搜索框绑定的treeFilter
    treeFilter(val) {
      this.$refs.tree.filter(val);
      // 当搜索框键入值改变时，将该值作为入参执行树形控件的过滤事件filterNode
    }
  },
}
</script>

<style scoped>
.input-name, .selectDaihao {
  width: auto !important;
}

.daihao-div {
  margin-top: 10px;
}

.myData {
  text-align: center;
}

.input {
  width: 99%;
}
</style>
